<template>
  <div class="setmeal-edit-container">
    <el-card class="form-card">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <!-- 基本信息区域 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <div class="form-row">
            <!-- 套餐名称 -->
            <el-form-item label="套餐名称" prop="name" class="form-item">
              <el-input v-model="formData.name" placeholder="请输入套餐名称" clearable style="width: 300px" />
            </el-form-item>

            <!-- 套餐分类 -->
            <el-form-item label="套餐分类" prop="categoryId" class="form-item">
              <el-select
                  v-model="formData.categoryId"
                  placeholder="请选择套餐分类"
                  clearable
                  style="width: 300px"
              >
                <el-option
                    v-for="category in categories"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                />
              </el-select>
            </el-form-item>
          </div>

          <div class="form-row">

            <!-- 套餐价格 -->
            <el-form-item label="套餐价格" prop="price" class="form-item">
              <el-input-number
                  v-model="formData.price"
                  :min="0"
                  :precision="2"
                  :step="1"
                  controls-position="right"
                  style="width: 300px"
              />
              <span class="unit">元</span>
            </el-form-item>

            <!-- 菜品图片 -->
            <el-form-item label="菜品图片" prop="image">
              <el-upload
                  class="image-uploader"
                  :show-file-list="false"
                  :before-upload="beforeImageUpload"
                  :http-request="customUpload"
                  accept="image/*"
              >
                <div class="image-preview">
                  <!-- 加载状态 -->
                  <div v-if="uploadLoading" class="upload-mask">
                    <el-icon class="is-loading"><Loading /></el-icon>
                    <span class="ml-2">上传中...</span>
                  </div>

                  <!-- 预览显示 -->
                  <img v-if="formData.imagePreview" :src="formData.imagePreview" class="dish-image" />
                  <el-icon v-else class="uploader-icon"><Plus /></el-icon>
                </div>
              </el-upload>
            </el-form-item>
          </div>

          <!-- 套餐描述 -->
          <el-form-item label="套餐描述" prop="description" class="form-item">
            <el-input
                v-model="formData.description"
                type="textarea"
                :rows="3"
                placeholder="请输入套餐描述"
                style="width: 610px"
            />
          </el-form-item>
        </div>

        <!-- 套餐菜品区域 -->
        <div class="form-section">
          <h3 class="section-title">套餐菜品</h3>
          <el-form-item prop="setmealDishes" class="form-item">
            <el-button type="primary" @click="showDishDialog = true">
              选择菜品
            </el-button>
            <div v-if="formData.setmealDishes?.length" class="selected-dishes">
              <div v-for="dish in formData.setmealDishes" :key="dish.dishId" class="dish-item">
                <span>{{ dish.name }} (x{{ dish.copies }})</span>
                <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    circle
                    @click="removeDish(dish.dishId)"
                />
              </div>
            </div>
            <div v-else class="empty-tip">暂未选择菜品</div>
          </el-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 选择菜品的对话框 -->
    <el-dialog v-model="showDishDialog" title="选择菜品" width="900px" class="dish-dialog">
      <div class="dish-selector">
        <!-- 左侧分类 -->
        <div class="category-side">
          <el-input
              v-model="dishSearchQuery"
              placeholder="搜索菜品"
              clearable
              @clear="searchDishes"
              @keyup.enter="searchDishes"
              style="margin-bottom: 10px"
          >
            <template #append>
              <el-button :icon="Search" @click="searchDishes" />
            </template>
          </el-input>
          <el-tree
              :data="dishCategories"
              :props="categoryProps"
              node-key="id"
              :default-expand-all="true"
              :highlight-current="true"
              @node-click="handleCategoryClick"
              style="height: 400px; overflow: auto"
          />
        </div>

        <!-- 中间菜品列表 -->
        <div class="dish-list">
          <el-table :data="filteredDishes" height="400" border>
            <el-table-column prop="name" label="菜品名称" width="180" />
            <el-table-column prop="price" label="价格(元)" width="120">
              <template #default="{ row }">
                {{ row.price.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button
                    type="primary"
                    size="small"
                    @click="addDish(row)"
                    :disabled="isDishSelected(row.id)"
                >
                  添加
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 右侧已选菜品 -->
        <div class="selected-side">
          <h3 class="selected-title">已选菜品 ({{ selectedDishes.length }})</h3>
          <div class="selected-list">
            <div
                v-for="dish in selectedDishes"
                :key="dish.dishId"
                class="selected-item"
            >
              <div class="dish-info">
                <span class="dish-name">{{ dish.name }}</span>
                <el-input-number
                    v-model="dish.copies"
                    :min="1"
                    :max="99"
                    size="small"
                    controls-position="right"
                    style="width: 100px"
                />
              </div>
              <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  circle
                  @click="removeSelectedDish(dish.dishId)"
              />
            </div>
          </div>
          <!-- 添加小计区域 -->
          <div class="subtotal-area">
            <div class="subtotal-row">
              <span>菜品小计：</span>
              <span class="subtotal-amount">{{ calculateSubtotal().toFixed(2) }}元</span>
            </div>
          </div>

          <div class="dialog-footer">
            <el-button @click="showDishDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmDishes">确定</el-button>
          </div>
        </div>



      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import {useRoute, useRouter} from 'vue-router'
import { getCategoryByType } from '@/api/category'
import {getAllDish, getDishList} from '@/api/dish'
import { addSetMeal, updateSetMeal, getSetMealById } from '@/api/setmeal'
import {ElMessage} from "element-plus";
import {fileViewPath, uploadFile} from "@/utils/file";

// const props = defineProps({
//   id: {
//     type: [String, Number],
//     default: null
//   }
// })

// 分类数据
const categories = ref([])//套餐分类
const dishCategories = ref([])//菜品分类
const categoryProps = {
  label: 'name',
  children: 'children'
}

// 1.加载分类数据（添加/修改组件的套餐分类+对话框的菜品分类）
const loadCategories = async () => {
  try {
    // 加载套餐分类
    const res = await getCategoryByType(2) // 2表示套餐分类
    if (res.code === '200') {
      categories.value = res.data
    }else{
      ElMessage.error('获取套餐分类失败')
    }

    // 加载菜品分类
    const dishRes = await getCategoryByType(1) // 1表示菜品分类
    if (dishRes.code === '200') {
      dishCategories.value = dishRes.data
    }else{
      ElMessage.error('获取菜品分类失败')
    }
  } catch (error) {
    ElMessage.error("获取分类失败")
    console.error('加载分类失败:', error)
  }
}


const router = useRouter()

//表单校验
const formRef = ref(null)
// 表单数据
const formData = reactive({
  name: '',
  categoryId: null,
  price: 0,
  image: '',
  imagePreview: '',//前端展示图谱的完整url
  description: '',
  setmealDishes: []
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择套餐分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入套餐价格', trigger: 'blur' }],
  image: [
    { required: true, message: '请上传菜品图片', trigger: 'change' }
  ],
  setmealDishes: [
    { required: true, message: '请至少选择一个菜品', trigger: 'change' }
  ]
}
// 菜品对话框相关
const showDishDialog = ref(false)
const dishSearchQuery = ref('')
const allDishes = ref([])
const currentCategoryId = ref(null)
const selectedDishes = ref([])

// 菜品分类点击事件
const handleCategoryClick = (data) => {
  if (data.type === 1) { // 1表示菜品分类
    currentCategoryId.value = data.id
    loadDishes()//加载当前分类的菜品信息
  }
}
// 加载菜品数据
const loadDishes = async () => {
  try {
    const params = {
      categoryId: currentCategoryId.value,
      name: dishSearchQuery.value
    }
    const res = await getAllDish(params);
    if (res.code === '200') {
      allDishes.value = res.data;
    }else{
      allDishes.value = [];
      ElMessage.error(res.msg||'获取菜品失败')
    }
  } catch (error) {
    console.error('加载菜品失败:', error)
  }
}

const route = useRoute()
const isEditMode = ref(route.name === 'SetMealEdit')
// 加载套餐详情（编辑时）
const loadSetMealDetail = async () => {

  if (!isEditMode.value) return

  try {
    const res = await getSetMealById(route.params.id)
    if (res.code === '200') {
      Object.assign(formData, {
        ...res.data,
        imagePreview: `${fileViewPath}${formatImagePath(res.data.image)}`
      })
      // 初始化已选菜品
      selectedDishes.value = formData.setmealDishes.map(item => ({
        dishId: item.dishId,
        name: item.name,
        price: item.price,
        copies: item.copies
      }))
    }else{
      ElMessage.error(res.msg||'获取套餐详情失败')
    }
  } catch (error) {
    console.error('加载套餐详情失败:', error)
  }
}

/*文件上传*/
// 上传加载状态
const uploadLoading = ref(false)
// 路径格式化函数（处理Windows路径）
const formatImagePath = (path) => {
  if (!path) return '';
  return path.replace(/\\/g, '/'); // 将反斜杠替换为斜杠
};

// 自定义上传方法
const customUpload = async (options) => {
  try {
    uploadLoading.value = true

    // 创建 FormData
    const form = new FormData()
    form.append('file', options.file) // 后端接受文件的字段名

    // 调用上传接口
    const res = await uploadFile({
      url: '/file/upload',
      data: form
    })

    const {code,data,msg} = res.data;
    // 处理响应（根据实际接口结构调整）
    if (code === '200') {
      formData.image = formatImagePath(data)
      formData.imagePreview = `${fileViewPath}${formatImagePath(data)}`
      ElMessage.success('图片上传成功')
      return data;//返回上传成功
    } else {
      ElMessage.error(msg || '上传失败')
      return Promise.reject(msg)
    }
  } catch (error) {

    let errorMsg = '上传失败';
    if (error.response) {
      errorMsg = `服务器错误: ${error.response.status}`;
    } else if (error.message.includes('timeout')) {
      errorMsg = '请求超时，请重试';
    } else if (error.message) {
      errorMsg = error.message;
    }

    ElMessage.error(errorMsg);
    throw error; // 继续抛出错误供外部处理
  } finally {
    uploadLoading.value = false
  }
}
// 上传前校验
const beforeImageUpload = (file) => {
  // 文件类型验证
  const validTypes = ['image/jpeg', 'image/png', 'image/gif']
  const isImage = validTypes.includes(file.type)

  // 文件大小验证（2MB）
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('仅支持 JPG/PNG/GIF 格式!')
    return false
  }

  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 添加图片预览（可选）
  const reader = new FileReader()
  reader.onload = (e) => {
    // 临时显示本地预览
    formData.image = e.target.result
  }
  reader.readAsDataURL(file)

  return true
}


// 搜索菜品
const searchDishes = () => {
  currentCategoryId.value = null
  loadDishes()
}

// 过滤后的菜品列表
const filteredDishes = computed(() => {
  return allDishes.value.filter(
      dish => dish.status === 1 // 只显示在售的菜品
  )
})

// 检查菜品是否已选
const isDishSelected = (dishId) => {
  return selectedDishes.value.some(item => item.dishId === dishId)
}

// 添加菜品
const addDish = (dish) => {
  if (!isDishSelected(dish.id)) {
    selectedDishes.value.push({
      dishId: dish.id,
      name: dish.name,
      price: dish.price,
      copies: 1
    })
  }
}

// 计算已选菜品小计
const calculateSubtotal = () => {
  return selectedDishes.value.reduce((total, dish) => {
    return total + (dish.price * dish.copies)
  }, 0)
}

// 移除已选菜品
const removeSelectedDish = (dishId) => {
  const index = selectedDishes.value.findIndex(item => item.dishId === dishId)
  if (index !== -1) {
    selectedDishes.value.splice(index, 1)
  }
}

// 确认选择的菜品
const confirmDishes = () => {
  formData.setmealDishes = [...selectedDishes.value]
  showDishDialog.value = false
}

// 从表单中移除菜品
const removeDish = (dishId) => {
  const index = formData.setmealDishes.findIndex(item => item.dishId === dishId)
  if (index !== -1) {
    formData.setmealDishes.splice(index, 1)
    // 同时从已选菜品中移除
    removeSelectedDish(dishId)
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();

    if (isEditMode.value) {
      const submitFormData = {
        ...formData,
        id: route.params.id
      }
      console.log("sbf=",submitFormData)
      // 编辑套餐
      const res = await updateSetMeal(submitFormData)
      if(res.code === '200'){
        ElMessage.success(res.data||'编辑套餐成功')
        await router.push('/setmeal')
      }else{
        ElMessage.error(res.msg||'编辑套餐失败')
      }
    } else {
      // 新增套餐
      const submitDataForm = {
        ...formData,
        status: 1
      }
      const res = await addSetMeal(submitDataForm)
      if(res.code === '200'){
        ElMessage.success(res.data||'保存套餐成功')
        await router.push('/setmeal')
      }else{
        ElMessage.error(res.msg||'保存套餐失败')
      }
    }
  } catch (error) {
    console.error('保存套餐失败:', error)
  }
}

// 取消
const cancel = () => {
  router.push('/setmeal')
}

// 初始化
onMounted(async () => {
  await loadCategories()
  await loadSetMealDetail()
})
</script>

<style scoped>
.subtotal-area {
  padding: 10px;
  border-top: 1px solid #eee;
  margin-top: auto; /* 确保小计区域在底部 */
}

.setmeal-edit-container {
  padding: 20px;
}

.form-card {
  max-width: 1200px;
  margin: 0 auto;
}

.form-section {
  margin-bottom: 20px;
  padding: 40px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.section-title {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
  font-size: 16px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 0;
}

.unit {
  margin-left: 10px;
  color: #666;
}

.form-actions {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.image-uploader {
  width: 180px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.dish-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

/* 添加固定尺寸和预览样式 */
.image-preview {
  width: 180px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.dish-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.unit {
  margin-left: 10px;
  color: #666;
}

.unit {
  margin-left: 10px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.flavor-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.dish-image {
  width: 200px;
  height: 150px;
  display: block;
  cursor: pointer;
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
}
/* 已选菜品样式 */
.selected-dishes {
  margin-top: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 10px;
  max-width: 600px;
}

.dish-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
}

.dish-item:last-child {
  border-bottom: none;
}

.empty-tip {
  color: #999;
  font-size: 14px;
  margin-top: 10px;
}

/* 菜品选择对话框样式 */
.dish-dialog {
  .dish-selector {
    display: flex;
    height: 500px;
  }

  .category-side {
    width: 220px;
    padding-right: 15px;
    border-right: 1px solid #eee;
  }

  .dish-list {
    flex: 1;
    padding: 0 15px;
  }

  .selected-side {
    width: 250px;
    padding-left: 15px;
    border-left: 1px solid #eee;
    display: flex;
    flex-direction: column;
  }

  .selected-title {
    margin-top: 0;
    font-size: 16px;
  }

  .selected-list {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 15px;
  }

  .selected-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px dashed #eee;
  }

  .dish-info {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .dish-name {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style>